import * as fs from "fs";
import {Cell, CellRichTextValue, ValueType} from "exceljs";
import path = require("path");
import {copyFile, copyFileSync} from "fs";
import {ConfigDataEntity} from "./generate/entitas";


export interface PathObject{
	path:string
	fileName :string
	fullName :string
}
export class Utils
{
	static getFileListWithSuffix(dir, fileSuffix, filesList?) : Array<PathObject>{
		filesList = filesList || []
		let files = fs.readdirSync(dir);
		files.forEach(function (itm, index) {
			let fullPath = path.join(dir , itm);
			if (!fs.existsSync(fullPath)){
				return
			}
			const stat = fs.lstatSync(fullPath);
			if (stat.isDirectory()) {
				//递归读取文件
				utils.getFileListWithSuffix(fullPath, filesList)
			} else {
				const obj: any = {};//定义一个对象存放文件的路径和名字
				if (itm.endsWith(fileSuffix)){
					obj.path = dir;//路径
					obj.fileName = itm//名字
					obj.fullName = fullPath
					filesList.push(obj);
				}

			}
		})
		return filesList
	}

	public static writeFileSync(file, data, options = null){
		let dirName = path.dirname(file)
		if (!fs.existsSync(dirName)){
			fs.mkdirSync(dirName, {
				recursive: true  //是否递归,默认false
			})
		}
		fs.writeFileSync(file, data, options)
	}

	public static GetCellValue(cell : Cell){
		if (cell.type == ValueType.RichText){
			const richText = (cell.value as CellRichTextValue).richText;
			let strRet = ""
			for (let i = 0; i < richText.length; i++) {
				strRet += richText[i].text
			}
			return strRet
		}else{
			return cell.value
		}
	}

	public static LogErrorWithColumnEntity(info : string, columnEntity:ConfigDataEntity){
		const head = columnEntity.memberHeadData.value;
		const rootEntity = columnEntity.rootEntity.value;
		console.error(`Error:${info}, sheetName:${rootEntity.sheetName.value}, headInfo:${ head.headName.toString() + "  " + head.name + "  " + head.normalType}`)
	}

	//! 将srcDir文件下的文件、文件夹递归的复制到tarDir下
	public static copyFolder(srcDir, tarDir) {
		let files = fs.readdirSync(srcDir);
		files.forEach(function(file,index) {
			let srcPath = path.join(srcDir, file);
			let tarPath = path.join(tarDir, file);

			let stats =fs.statSync(srcPath)
			if (stats.isDirectory()) {
				console.log('mkdir', tarPath);
				fs.mkdir(tarPath, function(err) {
					if (err) {
						console.log(err);
						return;
					}

					utils.copyFolder(srcPath, tarPath);
				});
			} else {
				copyFileSync(srcPath, tarPath);
			}
		});
	}
}

// let ret = Utils.bracketMath("list<list<int>>")
// console.log(ret)
// ret = Utils.bracketMath("map<int,int>")
// console.log(ret)

